package com.ize.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ize.entity.dto.UserLoginDto;
import com.ize.entity.dto.UserLoginInfoDto;
import com.ize.entity.pojo.User;
import com.ize.entity.vo.UserLoginStateVo;
import com.ize.entity.vo.UserLoginVO;
import com.ize.mapper.UserMapper;
import com.ize.properties.JwtClaimsConstant;
import com.ize.properties.JwtProperties;
import com.ize.properties.WeChatProperties;
import com.ize.service.StudentService;
import com.ize.util.BaseContext;
import com.ize.util.HttpClientUtil;
import com.ize.util.MD5util;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.ize.util.JwtUtil;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class StudentServiceImpl implements StudentService {

    //微信服务接口地址
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    private final WeChatProperties weChatProperties;
    private final UserMapper userMapper;
    private final JwtProperties jwtProperties;

    /**
     * 微信一键登录
     * @param userLoginDto
     * @return
     */
    @Override
    public UserLoginVO login0(UserLoginDto userLoginDto) {
        String openid = getOpenid(userLoginDto.getCode());
        log.info("openid:{}", openid);
        //2.判断openid是否为空,如果为空登录表示失败,抛出业务异常
        if (openid==null){
            throw new RuntimeException("登录失败");
        }
        //3.判断用户是否为新用户
        LambdaQueryWrapper<User> lambdaWrapper = new LambdaQueryWrapper<>();
        lambdaWrapper.eq(/*对象中的变量指向数据库字段*/User::getOpenid,openid);
        User user = userMapper.selectOne(lambdaWrapper);
        //如果是新用户
        if (user==null){
            throw new RuntimeException("登录异常");
        }

        //4.登录成功生成token
        //生成令牌
        HashMap<String, Object> map = new HashMap<>();
        map.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);
        //5.返回用户对象
        UserLoginVO build = new UserLoginVO().builder()
                .token(token)
                .build();
        return build;
    }


    /**
     * 审核信息
     *
     * @param userLoginInfoDto
     * @return
     */
    @Override
    public UserLoginStateVo login1(UserLoginInfoDto userLoginInfoDto) {
        String studentId = userLoginInfoDto.getStudentId();
        String password = userLoginInfoDto.getPassword();
        String md5String = MD5util.getMD5String(password);
        //1.查询信息
        LambdaQueryWrapper<User> lambdaWrapper = new LambdaQueryWrapper<>();
        lambdaWrapper.eq(/*Doctor对象中的变量指向数据库字段*/User::getStudentId, studentId);
        lambdaWrapper.eq(User::getPassword, md5String);
        User user = userMapper.selectOne(lambdaWrapper);
        if (user==null){
            throw new RuntimeException("没有该用户（账号或密码错误）");
        }
        //2.微信绑定
        userMapper.updateUserState(userLoginInfoDto
                .getOpenid(),user.getId());
        log.info("成功绑定微信");
        UserLoginStateVo build = new UserLoginStateVo().builder()
                .state(user.getState())
                .build();
        return build;
    }


    /**
     * 获取状态
     * @param code
     * @return
     */
    @Override
    public UserLoginStateVo state(String code) {
        String openid = getOpenid(code);
        log.info("openid:{}", openid);
        //2.判断openid是否为空,如果为空登录表示失败,抛出业务异常
        if (openid==null){
            throw new RuntimeException("登录失败");
        }
        LambdaQueryWrapper<User> lambdaWrapper = new LambdaQueryWrapper<>();
        lambdaWrapper.eq(/*Doctor对象中的变量指向数据库字段*/User::getOpenid, openid);
        User user = userMapper.selectOne(lambdaWrapper);
        UserLoginStateVo userLoginStateVo = new UserLoginStateVo();
        if (user==null){
            //说明第一次登录
            userLoginStateVo.setState(0);
            userLoginStateVo.setOpenid(openid);
        }else{
            userLoginStateVo.setState(1);
        }

        return userLoginStateVo;
    }

    @Override
    public User info() {
        return userMapper.selectById(BaseContext.getCurrentId());
    }

    /**
     * 调用微信接口服务,来获取openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        //1.调用微信接口服务，获得当前用户的openId
        Map<String, String> map = new HashMap<String, String>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String s = HttpClientUtil.doGet(WX_LOGIN, map);
        //返回结果是Json形式数据,需要解析openid
        JSONObject jsonObject = JSON.parseObject(s);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
